package cn.zl.springbootredis.redis;

import cn.zl.springbootredis.SpringbootRedisApplication;
import cn.zl.springbootredis.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.UUID;

/**
 * @Description:
 * @Author: zhanglang
 * @Date: 2020/9/7 13:24
 */
//启动Springboot应用
@SpringBootTest(classes = SpringbootRedisApplication.class)
@RunWith(SpringRunner.class)
public class TestRedisTemplate {
    @Autowired
    private RedisTemplate redisTemplate;//key Object value Object ====>对象序列化

    //opsForxxx Vlaue String List Set Zset hash

    /**
     * redisTemplate对象中 key和value 的序列化都是 JdkSerializationRedisSerializer
     *    我们需要的是key为String字符串，value为Object对象
     *    修改默认key序列化方案：key StringRedisSerializer，而value默认就为object
     */
    @Test
    public void testRedisTemplate(){
        //修改key序列化方案 String类型序列
        redisTemplate.setKeySerializer(new StringRedisSerializer());

        //修改hash key的序列化方案
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        User user = new User();
        user.setId(Long.valueOf(UUID.randomUUID().toString())).setName("小陈").setAge(23).setEmail("zllwsy@outlook.com");
        redisTemplate.opsForValue().set("user",user);//redis进行设置  对象需要经过序列化
        User user1 = (User) redisTemplate.opsForValue().get("user");
        System.out.println(user1);

        redisTemplate.opsForList().leftPush("list",user);

        redisTemplate.opsForSet().add("set",user);

        redisTemplate.opsForZSet().add("zset",user,10);

        redisTemplate.opsForHash().put("map","name",user);
    }
}
